/**
 * 使用标志位进行线程中断
 */
public class ThreadExample6 {

    // 这里变量要定义为全局变量, 因为在 lambda 中使用局部变量会导致变量捕获
    static boolean isQuit = false;
    public static void main(String[] args) {

        Thread thread = new Thread(() -> {
            while (!isQuit) {
                try {
                    System.out.println(Thread.currentThread().getName() + " : I am alive!");
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            try {
                System.out.println(Thread.currentThread().getName() + " : I am leave in just one second!!");
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("I am leave~");
        }, "I'm spider man~");

        thread.start();

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Change isQuit~");
        isQuit = true;
    }
}
